{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 文件与文件系统"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "'b' 以二进制模式打开文件。一般用于非文本文件，如：图片。\n",
    "'t' 以文本模式打开（默认）。一般用于文本文件，如：txt。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f.read(x) x代表从文件中读取多少字符，如果没有设定，读取全部\n",
    "f.raedline() 读取整行，包括换行符\n",
    "f.raedlines() 读取所有的行，返回list 可以配合for in 进行处理\n",
    "f.tell()返回文件指针的当前位置\n",
    "f.seek(offset[, whence]) 用于移动文件读取指针到指定位置。\n",
    "    a. offset ：开始的偏移量，也就是代表需要移动偏移的字节数，如果是负数表示从倒数第几位开始。\n",
    "    b. whence ：可选，默认值为 0。给 offset 定义一个参数，表示要从哪个位置开始偏移；0 代表从文件开\n",
    "    头开始算起，1 代表从当前位置开始算起，2 代表从文件末尾算起。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "小马的程序人生\n",
      "\n",
      "老马的程序人生\n"
     ]
    }
   ],
   "source": [
    "#f.writelines()如要换行则自己加入\\n\n",
    "f = open('test.txt', 'w+')\n",
    "seq = ['小马的程序人生\\n', '老马的程序人生']\n",
    "f.writelines(seq)\n",
    "f.seek(0, 0)  #如果不加这一行 指针改不过来\n",
    "for each in f:\n",
    "    print(each)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "出错啦!not readable\n"
     ]
    }
   ],
   "source": [
    "#即使读文件报错 也会关闭文件\n",
    "try:\n",
    "    f = open('myfile.txt', 'w')\n",
    "    for line in f:\n",
    "        print(line)\n",
    "except OSError as error:\n",
    "    print('出错啦!%s' % str(error))\n",
    "finally: #\n",
    "    f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# os操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当前工作目录 : C:\\Users\\闫厚镇\\Desktop\\datawhale学习\\python基础\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "#os.getcwd 得到当前工作路径\n",
    "print(\"当前工作目录 : %s\" % os.getcwd())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "目录修改成功 : C:\\\n"
     ]
    }
   ],
   "source": [
    "# os.chdir  更改工作目录\n",
    "path = 'C:\\\\'\n",
    "os.chdir(path)\n",
    "print(\"目录修改成功 : %s\" % os.getcwd())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "$Recycle.Bin\n",
      "$WINDOWS.~BT\n",
      "AMD\n",
      "AMTAG.BIN\n",
      "bootTel.dat\n",
      "config.ini\n",
      "Config.Msi\n",
      "Documents and Settings\n",
      "HG\n",
      "hiberfil.sys\n",
      "inetpub\n",
      "LenovoDrivers\n",
      "LenovoQMDownload\n",
      "Log\n",
      "MPlugin.dll\n",
      "MSOCache\n",
      "OneDriveTemp\n",
      "pagefile.sys\n",
      "PerfLogs\n",
      "Program Files\n",
      "Program Files (x86)\n",
      "ProgramData\n",
      "Recovery\n",
      "SPlugin.dll\n",
      "swapfile.sys\n",
      "System Volume Information\n",
      "temp\n",
      "Users\n",
      "WiFi_Log.txt\n",
      "Windows\n"
     ]
    }
   ],
   "source": [
    "#listdir (path='.') 返回 path 指定的文件夹包含的文件或文件夹的名字的列表。\n",
    "import os\n",
    "dirs = os.listdir()\n",
    "for item in dirs:\n",
    "    print(item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "#os.mkdir(path) 创建单层目录，如果该目录已存在抛出异常。\n",
    "import os\n",
    "if os.path.isdir(r'.\\b') is False:\n",
    "    os.mkdir(r'.\\B')\n",
    "    os.mkdir(r'.\\B\\A')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "$Recycle.Bin\n",
      "$WINDOWS.~BT\n",
      "AMD\n",
      "AMTAG.BIN\n",
      "B\n",
      "bootTel.dat\n",
      "config.ini\n",
      "Config.Msi\n",
      "Documents and Settings\n",
      "HG\n",
      "hiberfil.sys\n",
      "inetpub\n",
      "LenovoDrivers\n",
      "LenovoQMDownload\n",
      "Log\n",
      "MPlugin.dll\n",
      "MSOCache\n",
      "OneDriveTemp\n",
      "pagefile.sys\n",
      "PerfLogs\n",
      "Program Files\n",
      "Program Files (x86)\n",
      "ProgramData\n",
      "Recovery\n",
      "SPlugin.dll\n",
      "swapfile.sys\n",
      "System Volume Information\n",
      "temp\n",
      "Users\n",
      "WiFi_Log.txt\n",
      "Windows\n"
     ]
    }
   ],
   "source": [
    "dirs = os.listdir()\n",
    "for item in dirs:\n",
    "    print(item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "os.remove(path) 用于删除指定路径的文件。如果指定的路径是一个目录，将抛出 OSError"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "os.system(command) 运行系统的shell命令（将字符串转化成命令）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import os\n",
    "path = os.getcwd() + '\\\\a.py'\n",
    "a = os.system(r'python %s' % path)\n",
    "os.system('calc')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      ".\n",
      "..\n",
      "\\\n",
      "\r\n",
      "\n",
      "nt\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "print(os.curdir) # .\n",
    "print(os.pardir) # ..\n",
    "print(os.sep) # 出操作系统特定的路径分隔符\n",
    "print(os.linesep)# 当前平台使用的行终止符\n",
    "print(os.name)#指代当前使用的操作系统"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "1. os.path.basename(path) 去掉目录路径，单独返回文件名\n",
    "2. os.path.dirname(path) 去掉文件名，单独返回目录路径\n",
    "3. os.path.join(path1[, path2[, ...]]) 将 path1 ， path2 各部分组合成一个路径名\n",
    "4. os.path.split(path) 分割文件名与路径，返回 (f_path,f_name) 元组。如果完全使用目录，它会将最后\n",
    "   一个目录作为文件名分离，且不会判断文件或者目录是否存在。\n",
    "5. os.path.splitext(path) 分离文件名与扩展名，返回 (f_path,f_name) 元组。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "1. os.path.getsize(file) 返回指定文件大小，单位是字节。\n",
    "2. os.path.getatime(file) 返回指定文件最近的访问时间\n",
    "3. os.path.getctime(file) 返回指定文件的创建时间\n",
    "4. os.path.getmtime(file) 返回指定文件的最新的修改时间\n",
    "5. 浮点型秒数，可用time模块的 gmtime() 或 localtime() 函数换算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "1. os.path.exists(path) 判断指定路径（目录或文件）是否存在\n",
    "2. os.path.isabs(path) 判断指定路径是否为绝对路径\n",
    "3. os.path.isdir(path) 判断指定路径是否存在且是一个目录\n",
    "4. os.path.isfile(path) 判断指定路径是否存在且是一个文件\n",
    "5. os.path.islink(path) 判断指定路径是否存在且是一个符号链接\n",
    "6. os.path.ismount(path) 判断指定路径是否存在且是一个悬挂点\n",
    "7. os.path.samefile(path1,path2) 判断path1和path2两个路径是否指向同一个文件"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 序列化与反序列化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "可能在保存模型是用到的比较多\n",
    "pickle.dump(想要保存的对象，保存路径）  保存路径最好先用open打卡\n",
    "pickle.load(保存路径)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle\n",
    "dataList = [[1, 1, 'yes'],\n",
    " [1, 1, 'yes'],\n",
    " [1, 0, 'no'],\n",
    " [0, 1, 'no'],\n",
    " [0, 1, 'no']]\n",
    "dataDic = {0: [1, 2, 3, 4],\n",
    " 1: ('a', 'b'),\n",
    " 2: {'c': 'yes', 'd': 'no'}}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "fw = open(r'.\\dataFile.pkl', 'wb')\n",
    "pickle.dump(dataList, fw, -1)\n",
    "pickle.dump(dataDic, fw)\n",
    "fw.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "data1 [[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]\n",
      "data2 {0: [1, 2, 3, 4], 1: ('a', 'b'), 2: {'c': 'yes', 'd': 'no'}}\n"
     ]
    }
   ],
   "source": [
    "# 使用load()将数据从文件中序列化读出\n",
    "fr = open('dataFile.pkl', 'rb')\n",
    "data1 = pickle.load(fr)\n",
    "print(\"data1\",data1)\n",
    "data2 = pickle.load(fr)\n",
    "print('data2',data2)\n",
    "fr.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
